<template>
  <div class="app-container">
    <div class="app-container-inner">
      <div v-if="userStore.utype == 3">
        <div style="margin-bottom: 2%; margin-left: 2%">
          <el-form :inline="true" :model="queryForm" class="demo-form-inline">
            <el-form-item label="管理员姓名">
              <el-input v-model="queryForm.name" clearable />
            </el-form-item>
            <el-form-item label="管理员工号">
              <el-input v-model="queryForm.num" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="query">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="sendActivity">发送公告</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="batchSend">批量发送信息</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" :reserve-selection="true" width="30" />
          <el-table-column property="name" label="管理员姓名" width="120" />
          <el-table-column property="num" label="管理员工号" width="120" />
          <el-table-column property="email" label="邮箱" width="250" />
          <el-table-column property="phone" label="手机号" width="140" />
          <el-table-column property="branch_name" label="党支部名称" width="140" />
          <el-table-column property="create_date" label="支部创建时间" width="140" />
          <el-table-column property="operation" label="操作">
            <template #default="scope">
              <el-button size="small" type="success" @click="sendNotice(scope.$index, scope.row)"
                >发送通知</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next"
          style="margin-left: 65%; margin-top: 2%"
          small
          :total="total"
          @current-change="handelCurrentChange"
          v-model:current-page="currentPage"
        />
        <div>
          <el-dialog v-model="VisSendNotice" title="发送通知" width="80%">
            <div style="margin-bottom: 2%">
              <el-input v-model="noticeTitle" placeholder="通知标题">
                <template #prepend>标题</template>
              </el-input>
            </div>
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="send">发送</el-button>
            <el-button @click="VisSendNotice = false">取消</el-button>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="VisNotice" title="批量发送通知" width="80%">
            <div style="margin-bottom: 2%">
              <el-input v-model="noticeTitle" placeholder="通知标题">
                <template #prepend>标题</template>
              </el-input>
            </div>
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="batchSendNotice">发送</el-button>
            <el-button @click="VisNotice = false">取消</el-button>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="Visible" title="发送公告" width="80%">
            <div style="margin-bottom: 2%">
              <el-input v-model="activityTitle" placeholder="公告标题">
                <template #prepend>标题</template>
              </el-input>
            </div>
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="sendAct">发送</el-button>
            <el-button @click="Visible = false">取消</el-button>
          </el-dialog></div
        >
      </div>
      <div v-else>
        <Error />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="comprehensive">
  import { ref, onMounted, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import watermark from '@/utils/watermark.js'
  import { Cloud } from 'laf-client-sdk'
  import { getAllBranch, getBranchID } from '@/lafSdkCollection/getPartyMember'
  import Wangeditor from '../../components/WangEdior/index.vue'
  import { useUserStore } from '@/store/modules/user'
  import Error from '@/views/error/403.vue'
  const APPID = 'su75ks' // Laf 应用 appid
  const cloud = new Cloud({
    baseUrl: `https://${APPID}.laf.run`,
    getAccessToken: () => userStore.token,
  })
  const userStore = useUserStore()
  const loading = ref(true)
  const multipleTableRef = ref()
  const select_order_number = ref() //表格select选中的条数
  const select_orderId = ref([]) //表格select复选框选中的id
  const select_order_num = ref([]) //表格select复选框选中的num
  const multipleSelection = ref([])
  const editorContent = ref('') //富文本编辑器内容，就是一段html代码
  const activityTitle = ref('')

  //选中的list
  const getRowKeys = (row) => {
    //记录每行的key值
    return row.id
  }
  //当表格选择项发生变化时会触发该事件
  const handleSelectionChange = (val) => {
    // 解决来回切换页面，也无法清除上次选中情况
    multipleSelection.value = val
    select_order_number.value = multipleSelection.value.length
    select_orderId.value = []
    select_order_num.value = []
    if (val) {
      undefined
      val.forEach((row) => {
        undefined
        if (row) {
          undefined
          select_orderId.value.push(row.id)
          select_order_num.value.push(row.num)
        }
      })
    }
  }

  const batchSend = () => {
    if (select_order_num.value.length == 0) {
      ElMessage('请先选择')
      return
    }
    VisNotice.value = true
  }
  const VisNotice = ref(false)
  const batchSendNotice = async () => {
    let size = select_order_number.value
    if (size == 0) {
      ElMessage('请先选择')
      return
    }
    for (let i = 0; i < size; i++) {
      const receiver_id = await getBranchID(select_order_num.value[i])
      const data = {
        sender_id: userStore._id,
        utype: 2,
        title: noticeTitle.value,
        content: editorContent.value,
        receiver_id: receiver_id,
      }
      const res = await cloud.invoke('send_message', data)
      if (i == 0 && res.code == 201) {
        ElMessage(res.msg)
        VisNotice.value = false
      } else if (i == 0 && res.code == 400) {
        ElMessage(res.error)
      }
    }
  }
  const tableData = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const Visible = ref(false)
  const tableDataCopy = ref([])
  //获取当前页数
  const handelCurrentChange = async (nowPage) => {
    //获取当前页码
    currentPage.value = nowPage
  }
  const queryForm = ref({
    name: '',
    num: '',
  })
  const query = () => {
    tableData.value = tableDataCopy.value
    if (queryForm.value.name == '' && queryForm.value.num == '') {
      ElMessage('请先选择搜索条件')
      return
    }
    const judge = {
      name: queryForm.value.name == '' ? false : true,
      num: queryForm.value.num == '' ? false : true,
    }
    const searchData = []
    if (judge.name) {
      searchData.push({ name: queryForm.value.name })
    }
    if (judge.num) {
      searchData.push({ num: queryForm.value.num })
    }
    tableData.value = tableData.value.filter((item) => {
      let isShow = searchData.every((prop) => {
        let key = Object.keys(prop)[0]
        let value = prop[key]
        return item.hasOwnProperty(key) && item[key] === value
      })
      return isShow
    })
  }
  const sendNotice = (index, row) => {
    VisSendNotice.value = true
    num.value = row.num
  }
  const sendActivity = () => {
    Visible.value = true
  }
  const sendAct = async () => {
    const data = {
      sender_id: userStore._id,
      utype: 1,
      title: activityTitle.value,
      content: editorContent.value,
      receiver_id: '',
    }
    const res = await cloud.invoke('send_message', data)
    if (res.code == 201) {
      ElMessage(res.msg)
      Visible.value = false
    } else if (res.code == 404) {
      ElMessage(res.error)
    }
  }
  const send = async () => {
    const receiver_id = await getBranchID(num.value)
    const data = {
      sender_id: userStore._id,
      utype: 2,
      title: noticeTitle.value,
      content: editorContent.value,
      receiver_id: receiver_id,
    }
    const res = await cloud.invoke('send_message', data)
    if (res.code == 201) {
      ElMessage(res.msg)
      VisSendNotice.value = false
    } else if (res.code == 404) {
      ElMessage(res.error)
    }
  }
  const noticeTitle = ref('')
  const VisSendNotice = ref(false)
  const num = ref('')

  const PartyBranch = async () => {
    const res = await getAllBranch()
    let size = res.data.length
    tableData.value = []
    for (let i = 0; i < size; i++) {
      let str = res.data[i].info.create_date
      let batchDate = str.substring(0, 10)
      tableData.value.push({
        name: res.data[i].name,
        num: res.data[i].num,
        email: res.data[i].email,
        phone: res.data[i].phone,
        branch_name: res.data[i].info.branch_name,
        create_date: batchDate,
      })
    }
    tableDataCopy.value = tableData.value
  }
  const setWaterMark = () => {
    //添加水印
    watermark.set(userStore.college_name, userStore.num)
    //移除水印,传 null 移除水印
    //watermark.close()
  }
  onUnmounted(async () => {
    watermark.close(null)
  })
  onMounted(async () => {
    setWaterMark()
    await PartyBranch()
    tableDataCopy.value = tableData.value
    setTimeout(() => {
      loading.value = false
    }, 500)
  })
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
